//
//  MKRequest.m
//  yangtuner
//
//  Created by zhuwh on 2017/4/9.
//  Copyright © 2017年 maikevip. All rights reserved.
//

#import "MAKRequest.h"
#import "MAKResponse.h"
#import "YYModel.h"
#if __has_include(<MAKCommon/MAKMacros.h>)
#import <MAKCommon/MAKMacros.h>
#else
#import "MAKMacros.h"
#endif

#ifndef NSFoundationVersionNumber_iOS_8_0
#define NSFoundationVersionNumber_With_QoS_Available 1140.11
#else
#define NSFoundationVersionNumber_With_QoS_Available NSFoundationVersionNumber_iOS_8_0
#endif

static dispatch_queue_t makrequest_cache_writing_queue() {
    static dispatch_queue_t queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dispatch_queue_attr_t attr = DISPATCH_QUEUE_SERIAL;
        if (NSFoundationVersionNumber >= NSFoundationVersionNumber_With_QoS_Available) {
            attr = dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_BACKGROUND, 0);
        }
        queue = dispatch_queue_create("com.mark.app.MAKNet.caching", attr);
    });
    
    return queue;
}


@interface MAKRequest ()<YTKRequestAccessory,YTKChainRequestDelegate>

@property(nonatomic,assign)BOOL isHandleResponse;
@property(nonatomic,strong) YTKChainRequest* chainRequest;
@property(nonatomic,copy)MAKResponseSuccessBlock successBlock;
@property(nonatomic,copy)MAKResponseFailureBlock failureBlock;
@property(nonatomic,assign)BOOL needRefreshToken;

@end
@implementation MAKRequest

- (instancetype)init
{
    self = [super init];
    if (self) {
        //        [self addAccessory:self];
    }
    return self;
}

- (void)requestCompletePreprocessor {
    //    [super requestCompletePreprocessor];
    NSData* data = [super responseData];
    if (data) {
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",jsonDict);
    }
    if (!data&&[self.responseObject isKindOfClass:[NSDictionary class]]) {
        NSError *error;
        data = [NSJSONSerialization dataWithJSONObject:self.responseObject
                                               options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                 error:&error];
    }
    if (self.writeCacheAsynchronously) {
        dispatch_async(makrequest_cache_writing_queue(), ^{
            [self saveResponseDataToCacheFile:data];
        });
    } else {
        [self saveResponseDataToCacheFile:data];
    }
}

//请求结束处理
- (void)requestDidStop:(id)request{
    if (self.isHandleResponse) {
        return;
    }
    //失败处理
    if (self.error) {
        
    }else{
        //成功返回处理
        NSLog(@"%s",__func__);
    }
}

- (void)mak_startWithCompletionBlockWithSuccess:(MAKResponseSuccessBlock)success blockFailure:(MAKResponseFailureBlock)failure{
    NSLog(@"请求数据日志信息:%@",self.description);
    self.successBlock = success;
    self.failureBlock = failure;
    [self mak_start:NO];
}

-(BOOL)mak_needRefreshToken{
    return NO;
}

-(void)mak_refreshTokenCallBack:(id)response{

}

-(void)mak_start:(BOOL)ignoreExpirationTime{
    if (!ignoreExpirationTime) {
        if ([self mak_needRefreshToken]) {
            self.needRefreshToken = YES;
            MAKRequest* refreshTokenRequest = [self mak_refreshTokenRequest];
            if (refreshTokenRequest) {
                self.chainRequest = [YTKChainRequest new];
                self.chainRequest.delegate = self;
                MAK_WS(wSelf);
                [self.chainRequest addRequest:refreshTokenRequest callback:^(YTKChainRequest * _Nonnull chainRequest, YTKBaseRequest * _Nonnull baseRequest) {
                    NSDictionary* json = [baseRequest responseObject];
                    MAK_SS(sSelf);
                    id response = [[sSelf mak_responseClass] yy_modelWithDictionary:json];
                    [sSelf mak_refreshTokenCallBack:response];
                }];
                [self.chainRequest addRequest:self callback:nil];
                [self.chainRequest start];
            }
        }
    }
    if (ignoreExpirationTime||!self.needRefreshToken) {
        MAK_WS(wSelf);
        [self startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary* json = [request responseObject];
            MAK_SS(sSelf);
            id response = [[sSelf mak_responseClass] yy_modelWithDictionary:json];
            NSLog(@">>>>>>> %@",[response yy_modelDescription]);
            if(self.successBlock){
                if(!self.successBlock(response?:json)){
                    [response handelDefault];
                }
                [self mak_clearCompletionBlock];
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSLog(@"%@",[request error]);
            if (self.failureBlock) {
                self.failureBlock([request error]);
                [self mak_clearCompletionBlock];
            }
        }];
    }
}

-(void)mak_clearCompletionBlock{
    self.successBlock = nil;
    self.failureBlock = nil;
}

-(Class)mak_responseClass{
    return MAKResponse.class;
}

#pragma mark - YTKChainRequestDelegate
- (void)chainRequestFinished:(YTKChainRequest *)chainRequest {
    // all requests are done
    NSLog(@"%s",__func__);
    YTKBaseRequest* request = [chainRequest.requestArray lastObject];
    NSDictionary* json = [request responseObject];
    if(self.successBlock){
        id response = [[self mak_responseClass] yy_modelWithDictionary:json];
        NSLog(@">>>>>>> %@",[response yy_modelDescription]);
        if(!self.successBlock(response?:json)){
            [response handelDefault];
        }
        [self mak_clearCompletionBlock];
    }
}

- (void)chainRequestFailed:(YTKChainRequest *)chainRequest failedBaseRequest:(YTKBaseRequest*)request {
    // some one of request is failed
    NSLog(@"%s",__func__);
    if (chainRequest.requestArray.count==2) {
        //刷新token 失败
        //继续请求
        [self mak_start:YES];
    }else{
        if (self.failureBlock) {
            self.failureBlock([request error]);
            [self mak_clearCompletionBlock];
        }
    }
}

/**
 自定义解析器响应参数
 
 @param jsonResponse json响应
 @return 解析后的JSON
 */
- (id)mak_reformJSONResponse:(id)jsonResponse {
    if (!self.mak_modelClass) {
        return jsonResponse;
    } else {
        if ([jsonResponse isKindOfClass:[NSArray class]]) {
            return [NSArray yy_modelArrayWithClass:self.mak_modelClass json:jsonResponse];
        } else {
            return [self.mak_modelClass yy_modelWithJSON:jsonResponse];
        }
    }
    return nil;
}

- (BOOL)mak_handleError:(NSError*)error{
    return NO;
}
@end
